import { doLogin, doLogout } from "@/api/auth";
import type { LoginResult, Token } from "@/api/auth/type";
import { defineStore } from "pinia";
import { computed, ref } from "vue";
import { useUserStore } from "./user";
import type { User } from "@/api/user/type";
import router from "@/router";

export const useAuthStore = defineStore('auth', () => {
    const isLogin = ref(false)
    const token = ref({} as Token)
    const getToken = computed(() => `${token.value.prefix} ${token.value.content}`)
    const getIsLogin = computed(() => isLogin.value)
    const login = (username : string, password : string) : Promise<void> => {
        return doLogin({
            username, password, rememberMe: false,
            captcha: {
                captchaBase64: '',
                captchaKey: '',
                captchaCode: ''
            }
        }).then((res) => {
            const data = res.data as LoginResult;
            token.value = data.token;
            isLogin.value = true;
        });
    }
    function logout() {
        doLogout().then(() => {
            isLogin.value = false;
            token.value = {} as Token;
            const userStore = useUserStore();
            userStore.user = {} as User;
        });
    }
    async function init() {
        if (isLogin.value) {
            router.push("/");
        } else {
            goLogin();
        }
    }
    async function saveStatus() {
        // const store = await Store.load("store.auth");
        // if (store != null) {
        //     store.set("token", token.value);
        //     await store.save();
        // }
    }
    function goLogin() {
        router.push("/login");
    }
    return {
        token,
        getToken, getIsLogin,
        login, logout, init, goLogin
    }
})